package com.example.samples.controller;

import com.example.samples.Vo.Page;
import com.example.samples.Vo.RestTemplateUtil;
import com.example.samples.Vo.Result;
import com.example.samples.Vo.SamplePage;
import com.example.samples.bean.Sample;
import com.example.samples.service.SamplesService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
public class SampleController {

    //文件上传保存地址
    @Value("${sampleUrl.path}")
    private  String path;

    @Value("${sampleUrl.wais}")
    private  String wais;

    private SamplesService samplesService;

    public SampleController(SamplesService samplesService) {
        this.samplesService = samplesService;
    }


    @RequestMapping("/")
    public    String  index(){
        return  "index";
    }

    @GetMapping("/addSample")
    public ModelAndView addSample() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("addSample");
        return modelAndView;
    }

    @GetMapping("/uploadview")
    public String uploadview() {
        return "uploadadmin";
    }


    @RequestMapping("Sample/findAll")
    @ResponseBody
    public PageInfo  findAll(@RequestBody SamplePage page){

        return    samplesService.findAll(page);
    }


    @RequestMapping("Sample/findById")
    @ResponseBody
    public Sample  findById(Integer id){
        Sample  sample=samplesService.findById(id);
        if (sample!=null){
            if( sample.getFilePath()!=null) {
                sample.setFilePath(sample.getFilePath().replaceAll("\\\\", "/"));
            }
            if(sample.getFilePath()==null){
                sample.setFilePath("");
            }

        }
        return  sample;
    }

    @CrossOrigin
    @RequestMapping("Sample/externalFindById")
    @ResponseBody
    public Sample  externalFindById(HttpEntity<Integer>  request){
        Integer  id=request.getBody();
        Sample  sample=samplesService.findById(id);

        if (sample!=null){
            if( sample.getFilePath()!=null) {
                sample.setFilePath(sample.getFilePath().replaceAll("\\\\", "/"));
            }
            if(sample.getFilePath()==null){
                sample.setFilePath("");
            }

        }

        return  sample;
    }
    @CrossOrigin
    @RequestMapping("Sample/find")
    @ResponseBody
    public PageInfo  find( HttpEntity<SamplePage>  request){
      SamplePage  page=request.getBody();
        return  samplesService.findAll(page);
    }

    @CrossOrigin
    @RequestMapping("Sample/downloadShareFile")
    public String downLoad(String filename,String  names, HttpServletResponse response) throws UnsupportedEncodingException {
          filename=path+filename;
            File file = new File(filename);
            if (file.exists()) { //判断文件父目录是否存在
                //response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/force-download");
                response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(names, "UTF-8"));
                byte[] buffer = new byte[1024];
                FileInputStream fis = null; //文件输入流
                BufferedInputStream bis = null;
                OutputStream os = null; //输出流
                try {
                    os = response.getOutputStream();
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer);
                        i = bis.read(buffer);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                try {
                    bis.close();
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return null;
        }


    @CrossOrigin
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("fileName") String fileName, HttpServletRequest req) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) req).getFiles("file");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        String  filePath="false";
        String uuid = UUID.randomUUID().toString();
        for(int i=0;i<files.size();i++){
            MultipartFile file=files.get(i);
            if (file.isEmpty()) {
                return "";
            } else {
                //日期目录
                String format = sdf.format(new Date());
                format="/"+format;
                File folder = new File(path +format);
                if (!folder.isDirectory()) {
                    folder.mkdirs();
                }
                String oldName = file.getOriginalFilename();
                String newName =uuid+"_"+fileName+"_"+ (i) + oldName.substring(oldName.lastIndexOf("."), oldName.length());
                try {
                   // 文件保存
                    file.transferTo(new File(folder, newName));
                    // 返回上传文件的访问路径
                     filePath =format + newName;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return  filePath;

    }

    @CrossOrigin
    @RequestMapping("Sample/save")
    @ResponseBody
    public   int  Save(@RequestBody Sample sample){

        return  samplesService.save(sample);
    }

    @CrossOrigin
    @RequestMapping("Sample/deleteById")
    @ResponseBody
    public int  deleteById(Integer id){
       Sample  sample=   samplesService.findById(id);
        if(sample.getFilePath()==null){
            sample.setFilePath("");
        }
       for (int i=0;i<=sample.getFileNumber();i++){
           String  f=sample.getName().substring(0,sample.getName().lastIndexOf("."));
           String  s=sample.getName().substring(sample.getName().lastIndexOf("."),sample.getName().length());
           String  fileName=path+sample.getFilePath()+"/"+f+"_"+i+s;
           File file = new File(fileName);
           if(file.isFile() && file.exists())
               file.delete();
       }
       return   samplesService.deleteById(id);
    }

    @CrossOrigin
    @RequestMapping("Sample/Update")
    @ResponseBody
    public int update(@RequestBody Sample sample){

        return  samplesService.update(sample,path);
    }





}
